package com.gxa.controller;

import com.gxa.dto.ResultDto;
import com.gxa.util.Response;
import com.gxa.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SmsController {


    @Autowired
    private SmsUtil util;

    /**
     * 发送短信的方法
     * @param phone
     * @param session
     * @return
     */
    @PostMapping("/sms/send")
    public ResultDto send(String phone, HttpSession session){
        // 验证手机号
        // 获取验证码
        String code = util.getCode();
        // 保存到session中
        session.setAttribute("vcode", code);
        // 发送短信
        if (util.sendMessage(phone, code)) {
            return Response.success("发送成功！");
        }
        return Response.error(1001, "短信发送失败！");
    }

    /**
     * 验证验证码
     * @param vcode
     * @param session
     * @return
     */
    @PostMapping("/sms/check")
    public ResultDto checkVcode(String vcode, HttpSession session){
        // 先获取session中的验证码
        String vcode1 = (String) session.getAttribute("vcode");
        if (vcode.equals(vcode1)) {
            return Response.success("验证码正确！");
        }
        return Response.error(1002, "验证码错误！");

    }


}
